/*
 *  Copyright 2010 asustatil.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

package edu.upf.content;

import java.io.Serializable;
import java.awt.Container;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import edu.upf.utils.Definitions;
import edu.upf.utils.LogSystem;

/**
 * Class that creates a thumbnail of a given image
 * @author netjois
 */
public class Thumbnail implements Serializable, Definitions {

    LogSystem log;
    Image thumbImage;


    /**
     * Constructor of the thumbnail. Receives the path to original image
     * @param imgFilePath
     */
    public Thumbnail(String imgFilePath){
        log  = new LogSystem(Thumbnail.class);
        setThumbnail(imgFilePath);
    }

    /**
     * Gets the thumbnail as an Image java Object
     * @return
     */
    public Image getThumbnail() {
        return thumbImage;
    }

    /**
     * Sets the thumbnail associated by indicating the original image path
     * @param imgFilePath
     */
    public void setThumbnail(String imgFilePath) {
        Image image = Toolkit.getDefaultToolkit().getImage(imgFilePath);
        MediaTracker mediaTracker = new MediaTracker(new Container());
        mediaTracker.addImage(image, 0);
        try {
            mediaTracker.waitForID(0);
        } catch (InterruptedException ex) {
           log.addDebugLog(ex.getMessage());
        }
        double thumbRatio = (double) THUMBWIDTH / (double) THUMBHEIGHT;
        int imageWidth = image.getWidth(null);
        int imageHeight = image.getHeight(null);
        double imageRatio = (double) imageWidth / (double) imageHeight;
        int thumbHeight=THUMBHEIGHT, thumbWidth=THUMBWIDTH;
        if (thumbRatio < imageRatio) {
            thumbHeight = (int) (THUMBWIDTH / imageRatio);
        } else {
            thumbWidth = (int) (THUMBHEIGHT * imageRatio);
        }
        thumbImage = new BufferedImage(thumbWidth,thumbHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics2D = ((BufferedImage)thumbImage).createGraphics();
        graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);
    }
}
